package impl_v1.client;

import impl_v1.server.AuctioningSystemServer;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.InputMismatchException;
import java.util.Map;
import java.util.Scanner;

import model.AuctionPublic;
import model.exception.InvalidAuctionIDException;
import model.exception.InvalidPriceException;
import model.exception.UnavailableAuctionException;
import model.server.BuyerInterface;

public class BuyerClient {

	public static void main(String[] args) {

		try {
			BuyerInterface auctioningSystem = (BuyerInterface) Naming
					.lookup("rmi://localhost/AuctioningSystemService");

			Map<Integer, AuctionPublic> list;

			boolean end = false;
			Scanner scanner = new Scanner(System.in);
			String choice;
			do {
				System.out.println();
				System.out.println("Select auction to bid on :");

				list = auctioningSystem.listAuctionsPublic();
				if (list.isEmpty()) {
					System.out.println("(No auction yet. Press Enter to refresh.)");
					scanner.nextLine();
					continue;
				}
				for (Integer id : list.keySet()) {
					System.out.println(id + " : " + list.get(id));
				}
				System.out.println("(Press Enter to refresh.)");
				choice = scanner.nextLine();
				try {
					int auctionChosen = Integer.parseInt(choice);

					System.out.println("Price (int) :");
					int price = scanner.nextInt();
					scanner.nextLine();

					System.out.println("Name :");
					String name = scanner.nextLine();

					System.out.println("Email :");
					String email = scanner.nextLine();

					try {
						auctioningSystem.bid(auctionChosen, price, name, email);
					} catch (InvalidAuctionIDException e) {
						System.out.println("This auction doesn't exist!");
						continue;
					} catch (UnavailableAuctionException e) {
						System.out.println("Sorry, this auction is closed.");
						continue;
					} catch (InvalidPriceException e) {
						System.out.println("Your price is too low!");
						continue;
					}

					System.out.println("Successful bid");

				} catch (NumberFormatException | InputMismatchException e) {
					continue;
				}
			} while (!end);

			scanner.close();

		} catch (MalformedURLException | RemoteException | NotBoundException e) {
			System.err.println(AuctioningSystemServer.SERVER_REMOTE_EXCEPTION);
		}

	}
}
